/**
 * Created by dmrj on 2016/5/9.
 */
define(['jquery', 'appLocalStorage', 'appConst', 'model/global', 'common/widgetUtils', 'model/testData', 'model/report', 'stringUtils', 'appMessageBox', 'domReady!'], function ($, appLocalStorage, appConst, global, widgetUtils, testData, report, stringUtils, msgBox) {
    var that;
    var components = {};
    var data = {
        searchFields: {},
        searchSNParams: {},
        searchHistoryParams:{},
        searchItemParams: {},
        searchAttributes: {},
        attributeDatas: {},
        flag_history: true,
        flag_attribute: true
    };

    return {
        init: function () {
            that = this;
            components = {
                "tbl_sn": $("#tbl_sn"),
                "tbl_history": $("#tbl_history"),
                "tbl_attributes": $("#tbl_attributes"),
                "tbl_items": $("#tbl_items"),
                "wgt_report": $("#wid-id-0"),
                "collapseBtn1": $("#collapseBtn1"),
                "collapseBtn2": $("#collapseBtn2"),
                "collapseBtn3": $("#collapseBtn3"),
                "export_sn": $("#exportSN"),
                "export_history": $("#exportHistory"),
                "export_items": $("#exportItems"),
                "toggleTab": $('a[data-toggle="tab"]'),
                "tab_history": $("#widget-tab-3")
            };
            that.initSNTable();
            that.initHistoryTable();
            that.initAttrutesTable();
            that.initItemsTable();
            that.initExport();
            that.collapse(components.collapseBtn2);
            that.collapse(components.collapseBtn3);
        },

        collapse: function (collapseObj1) {
            var theOthers = collapseObj1.parent().nextAll("div, ul");
            var img = $(this).find('span > i');
            theOthers.toggle();

            if(theOthers.is(":hidden")) {
                img.removeClass('fa-angle-down');
                img.addClass('fa-angle-left');
            } else {
                img.removeClass('fa-angle-left');
                img.addClass('fa-angle-down');
            }
        },
        closeCollapse: function (collapseObj1) {
            var theOthers = collapseObj1.parent('div').nextAll("div, ul");
            var img = collapseObj1.find('span > i');
            if (theOthers.is(":hidden")) {
                img.removeClass('fa-angle-down');
                img.addClass('fa-angle-left');
            }
            else {
                img.removeClass('fa-angle-down');
                img.addClass('fa-angle-left');
                theOthers.toggle();
            }
        },
        openCollapse: function (collapseObj1) {
            var theOthers = collapseObj1.parent('div').nextAll("div, ul");
            var img = collapseObj1.find('span > i');
            if (theOthers.is(":hidden")) {
                img.removeClass('fa-angle-left');
                img.addClass('fa-angle-down');
                theOthers.toggle();
            }
            else {
                img.removeClass('fa-angle-left');
                img.addClass('fa-angle-down');
            }
        },
        initSNTable: function () {
            var customParams = function (params) {
                $.extend(params, data.searchSNParams);
                params['draw'] = params.draw;
                return params;
            };
            components.tbl_sn.dataTable({
                // "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>>r" +
                // "t" +
                // "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": true,
                "ordering": false,
                "ajax": {
                    "url": 'empty',
                    "type": "POST",
                    "dataSrc": "body",
                    "data": customParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "serialNumber"},
                    {"data": null},
                    {"data": "stationId"},
                    {"data": "slotNo"},
                    {"data": "startTime"},
                    {"data": "stopTime"},
                    {"data": "isPass"},
                    {"data": "idStr"}
                ],
                "columnDefs": [
                    {
                        "targets": [8],
                        "visible": false
                    },
                    {
                        "targets": [1],
                        "render": function (data, type, full) {
                            var serialNumber = data;
                            var url = "<a href='javascript:void(0);' class='searchHistory' name='" + serialNumber + "'>" + serialNumber + "</a>" +
                                "<a href='javascript:void(0);' name='" + serialNumber + "'><i class='fa fa-search pull-right' rel='tooltip' data-placement='right'" +
                                " data-original-title='" + $.i18n.prop('REPORT_DETAIL_TIP') + "' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [2],
                        "render": function (data, type, full) {
                            return full.projectName == null ? '-' : full.projectName;
                        }
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            return data == null ? '-' : data;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            return data;
                        }
                    }, {
                        "targets": [6],
                        "render": function (data, type, full) {
                            return data;
                        }
                    },
                    {
                        "targets": [7],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = '<span class="label label-success">' + $.i18n.prop('REPORT_PASS') + '</span>';
                            } else if (data == false) {
                                result = '<span class="label label-danger">' + $.i18n.prop('REPORT_FAIL') + '</span>';
                            }
                            return result;
                        }
                    }
                ],
                "initComplete": function () {
                    $("[rel=tooltip]").tooltip();
                }
            });

            global.drawNumber_bg(components.tbl_sn);

            components.tbl_sn.find("tbody").on('click','tr', function (e) {
                e.preventDefault();
                that.showHistoryBefore($(this).find(".searchHistory"));
                var searchParams = {
                    "search_EQ_stationIdOrSlotNo": data.searchFields.search_stationIdOrSlotNo,
                    "search_EQ_projectId": data.searchFields.search_projectId,
                    "search_EQ_projectName": data.searchFields.search_projectName,
                    "search_EQ_serialNumber": $(this).find(".searchHistory").attr("name")
                };
                data.searchAttributes = searchParams;
                searchParams.search_GTE_startTime = data.searchFields.search_startTime;
                searchParams.search_LTE_stopTime = data.searchFields.search_stopTime;
                data.searchHistoryParams = searchParams;

                if (components.tab_history.find(".active").find("a").attr("href") == "#hrh2") {
                    that.loadAttributeTable();
                }
                else {
                    that.loadHistoryTable();
                }
            });
        },
        loadSNData: function (fileds) {
            data.searchFields = fileds;
            that.reset();
            var searchParam = {
                "search_EQ_stationIdOrSlotNo": data.searchFields.search_stationIdOrSlotNo,
                "search_EQ_projectId": data.searchFields.search_projectId,
                "search_EQ_projectName": data.searchFields.search_projectName,
                "search_EQ_serialNumber": data.searchFields.search_serialNumber,
                "search_GTE_startTime": data.searchFields.search_startTime,
                "search_LTE_stopTime": data.searchFields.search_stopTime
            };

            data.searchSNParams = searchParam;

            widgetUtils.toggleWidgetLoading(components.wgt_report);
            components.tbl_sn.DataTable().ajax.url("history/serialNumber").load(function () {
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            });
        },

        showHistoryBefore: function (elementObj) {
            elementObj.parent().parent().addClass("active");
            elementObj.parent().parent().siblings().removeClass("active");
            components.collapseBtn2.parent().parent().find("strong").parent().remove();
            components.collapseBtn3.parent().parent().find("strong").parent().remove();
            components.collapseBtn2.parent().append("<span> " + $.i18n.prop("REPORT_SERIALNUMBER") +": <strong>" + elementObj.attr("name") + "</strong></span>");
            that.openCollapse(components.collapseBtn2);
            that.closeCollapse(components.collapseBtn3);
            appConst.clearTable(components.tbl_items);
            data.flag_attribute = true;
            data.flag_history = true;
        },
        initHistoryTable: function () {
            var customParams = function (params) {
                $.extend(params, data.searchHistoryParams);
                params['draw'] = params.draw;
                return params;
            };

            components.tbl_history.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": true,
                "ordering": false,
                "ajax": {
                    "url": 'empty',
                    "type": "POST",
                    "dataSrc": "body",
                    "data": customParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                        widgetUtils.toggleWidgetLoading(components.wgt_report);
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "stationId"},
                    {"data": "slotNo"},
                    {"data": "startTime"},
                    {"data": "stopTime"},
                    {"data": "isPass"},
                    {"data": "idStr"}
                ],
                "columnDefs": [
                    {
                        "targets": [6],
                        "visible": false
                    },
                    {
                        "targets": [1],
                        "render": function (data, type, full) {
                            var name = data == null ? '-' : data;
                            var url = "<a href='javascript:void(0);' class='searchItems' data-id='" + full.idStr + "' name='" + data + "'>" + name + "</a>" +
                                "<a href='javascript:void(0);' name='" + data + "'><i class='fa fa-searc" + $.i18n.prop('REPORT_DETAIL_TIP') + "' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            return data;
                        }
                    }, {
                        "targets": [4],
                        "render": function (data, type, full) {
                            return data;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = '<span class="label label-success">' + $.i18n.prop('REPORT_PASS') + '</span>';
                            } else if (data == false) {
                                result = '<span class="label label-danger">' + $.i18n.prop('REPORT_FAIL') + '</span>';
                            }
                            return result;
                        }
                    }
                ],
                "initComplete": function () {
                    $("[rel=tooltip]").tooltip();
                }
            });
            global.drawNumber_bg(components.tbl_history);
            components.tbl_history.find("tbody").on('click','tr', function (e) {
                e.preventDefault();
                that.showItemsBefore($(this).find(".searchItems"));
                that.loadItemsTable($(this).find(".searchItems").attr("data-id"));
            });

            components.toggleTab.on('shown.bs.tab', function (e) {
                if (($(this).attr("href") == "#hrh1") && (data.flag_history)) {
                    that.loadHistoryTable();
                }
            });
        },
        initAttrutesTable: function () {
            components.tbl_attributes.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing":true,
                "paging": true,
                "autoWidth": false,
                "stateSave": true,
                "language": appConst.table_language(),
                "ordering": false
            });
            global.drawNumber_ui(components.tbl_attributes);
            components.tbl_attributes.find("tbody").on('click','tr', function (e) {
                e.preventDefault();
                $(this).siblings().removeClass("active");
                $(this).addClass("active");
            });

            components.toggleTab.on('shown.bs.tab', function (e) {
                if (($(this).attr("href") == "#hrh2") && (data.flag_attribute)) {
                    that.loadAttributeTable();
                }
            });
        },
        loadHistoryTable: function () {
            widgetUtils.toggleWidgetLoading(components.wgt_report);
            components.tbl_history.DataTable().ajax.url("history/queryStation").load(function () {
                data.flag_history = false;
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            });
        },
        loadAttributeTable: function () {
            widgetUtils.toggleWidgetLoading(components.wgt_report);
            report.searchAttributes(data.searchAttributes, function (d) {
                data.attributeDatas = [];
                var array = new Array();
                $(d).each(function (i, e) {
                    var arr = new Array();
                    arr.push(null);
                    arr.push(e.attributeName);
                    arr.push(e.attributeValue);
                    array.push(arr);
                });
                data.attributeDatas = array;
                components.tbl_attributes.dataTable().api().clear().draw();
                components.tbl_attributes.dataTable().api().rows.add(data.attributeDatas).draw();
                widgetUtils.toggleWidgetLoading(components.wgt_report);
                data.flag_attribute = false;
            },
                function (d) {
                    widgetUtils.toggleWidgetLoading(components.wgt_report);
                });
        },

        showItemsBefore: function (elementObj) {
            elementObj.parent().parent().addClass("active");
            elementObj.parent().parent().siblings().removeClass("active");
            components.collapseBtn3.parent().parent().find("strong").parent().remove();
            components.collapseBtn3.parent().append("<span> " + $.i18n.prop("REPORT_STATIONNAME") +": <strong>" + elementObj.attr("name") + "</strong></span>");
            that.openCollapse(components.collapseBtn3);
        },
        initItemsTable: function () {
            var customParams = function (params) {
                $.extend(params, data.searchItemParams);
                params['draw'] = params.draw;
                return params;
            };
            components.tbl_items.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": true,
                "ordering": false,
                "ajax": {
                    "url": 'empty',
                    "type": "POST",
                    "dataSrc": "body",
                    "data": customParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                        widgetUtils.toggleWidgetLoading(components.wgt_report);
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "name"},
                    {"data": "upperLimit"},
                    {"data": "lowerLimit"},
                    {"data": "unitName"},
                    {"data": "testedValue"},
                    {"data": "isPass"}
                ],
                "columnDefs": [
                    {
                        "targets": [6],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = '<span class="label label-success">' + $.i18n.prop('REPORT_PASS') + '</span>';
                            } else if (data == false) {
                                result = '<span class="label label-danger">' + $.i18n.prop('REPORT_FAIL') + '</span>';
                            }
                            return result;
                        }
                    }
                ],
                "initComplete": function () {
                    $("[rel=tooltip]").tooltip();
                }
            });

            global.drawNumber_bg(components.tbl_items);
            components.tbl_items.find("tbody").on('click','tr', function (e) {
                e.preventDefault();
                $(this).siblings().removeClass("active");
                $(this).addClass("active");
            });
        },
        loadItemsTable: function (id) {
            var searchParams = {
                "search_EQ_projectId": data.searchFields.search_projectId,
                'search_EQ_id': id
            };

            data.searchItemParams = searchParams;
            widgetUtils.toggleWidgetLoading(components.wgt_report);
            components.tbl_items.DataTable().ajax.url("history/queryItem").load(function () {
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            });
        },
        initExport: function () {
            components.export_sn.click(function () {
                var params = stringUtils.getExportParams(data.searchSNParams);
                $(this).attr("href", "report/snView/xls?" + params);
            });

            components.export_history.click(function () {
                var params = stringUtils.getExportParams(data.searchHistoryParams);
                $(this).attr("href", "report/stationView/xls?" + params);
            });

            components.export_items.click(function () {
                var params = stringUtils.getExportParams(data.searchItemParams);
                $(this).attr("href", "report/testItemView/xls?" + params);
            });
        },
        reset: function () {
            that.closeCollapse(components.collapseBtn2);
            that.closeCollapse(components.collapseBtn3);
            components.collapseBtn2.parent().parent().find("strong").parent().remove();
            components.collapseBtn3.parent().parent().find("strong").parent().remove();
            appConst.clearTable(components.tbl_history);
            data.attributeDatas = {};
            appConst.clearTable(components.tbl_items);
        }
    };
});